package com.android.boncen.commonFrame;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.android.boncen.commonFrame.bean.UserBean;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * 功能描述:注册
 *
 * @date 2017/2/9
 */

public class RegistActivity extends FragmentActivity {
    @BindView(R.id.etName)
    EditText etName;
    @BindView(R.id.etPWD)
    EditText etPWD;
    @BindView(R.id.rb)
    RadioGroup rb;

    private ProgressDialog waitDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        ButterKnife.bind(this);
        waitDialog = new ProgressDialog(this);
        waitDialog.setMessage("正在处理");

    }

    @OnClick({R.id.btLogin})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btLogin:
                waitDialog.show();
                regist(etName.getText().toString(), etPWD.getText().toString());
                break;
        }
    }

    private void regist(final String name, final String pwd) {
        UserBean user = new UserBean();
        // true 男 false 女
        user.setSex(rb.getCheckedRadioButtonId() == R.id.brN);
        user.setUsername(name);
        user.setPassword(pwd);
        user.signUp(new SaveListener<BmobUser>() {
            @Override
            public void done(BmobUser bmobUser, BmobException e) {
                waitDialog.dismiss();
                if (e == null) {

                    login(name, pwd);

                } else {
                    Toast.makeText(RegistActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void login(String name, String pwd) {
        UserBean user = new UserBean();
        user.setUsername(name);
        user.setPassword(pwd);
        user.login(new SaveListener<BmobUser>() {
            @Override
            public void done(BmobUser bmobUser, BmobException e) {
                waitDialog.dismiss();
                if (e == null) {

                    startActivity(new Intent(RegistActivity.this, MainActivity.class));
                    finish();
                } else {
                    Toast.makeText(RegistActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
